package pe.gob.onpe.facade;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pe.gob.onpe.ejb.LogUtil;
import pe.gob.onpe.ejb.PadronElectoralSolicitante;
import pe.gob.onpe.ejb.id.PadronElectoralSolicitanteId;
import pe.gob.onpe.facade.local.PadronElectoralSolicitanteFacadeLocal;
import pe.gob.onpe.facade.remote.PadronElectoralSolicitanteFacadeRemote;


/**
 * Facade for entity PadronElectoralSolicitante.
 * 
 * @see pe.gob.onpe.ejb.PadronElectoralSolicitante
 * @author MyEclipse Persistence Tools
 */
@Stateless
public class PadronElectoralSolicitanteFacade implements
		PadronElectoralSolicitanteFacadeLocal,
		PadronElectoralSolicitanteFacadeRemote {
	// property constants
	public static final String NOMBRE = "nombre";
	public static final String APELLIDOPATERNO = "apellidopaterno";
	public static final String APELLIDOMATERNO = "apellidomaterno";
	public static final String IDINCONSISTENCIA = "idinconsistencia";
	public static final String ESTADOINCONSISTENCIA = "estadoinconsistencia";
	public static final String DESCRIPCIONINCONSISTENCIA = "descripcioninconsistencia";
	
	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Perform an initial save of a previously unsaved
	 * PadronElectoralSolicitante entity. All subsequent persist actions of this
	 * entity should use the #update() method.
	 * 
	 * @param entity
	 *            PadronElectoralSolicitante entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(PadronElectoralSolicitante entity) {
		LogUtil.log("saving PadronElectoralSolicitante instance", Level.INFO,
				null);
		try {
			entityManager.persist(entity);
			LogUtil.log("save successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("save failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Delete a persistent PadronElectoralSolicitante entity.
	 * 
	 * @param entity
	 *            PadronElectoralSolicitante entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(PadronElectoralSolicitante entity) {
		LogUtil.log("deleting PadronElectoralSolicitante instance", Level.INFO,
				null);
		try {
			entity = entityManager.getReference(
					PadronElectoralSolicitante.class, entity.getId());
			entityManager.remove(entity);
			LogUtil.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved PadronElectoralSolicitante entity and return
	 * it or a copy of it to the sender. A copy of the
	 * PadronElectoralSolicitante entity parameter is returned when the JPA
	 * persistence mechanism has not previously been tracking the updated
	 * entity.
	 * 
	 * @param entity
	 *            PadronElectoralSolicitante entity to update
	 * @returns PadronElectoralSolicitante the persisted
	 *          PadronElectoralSolicitante entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public PadronElectoralSolicitante update(PadronElectoralSolicitante entity) {
		LogUtil.log("updating PadronElectoralSolicitante instance", Level.INFO,
				null);
		try {
			PadronElectoralSolicitante result = entityManager.merge(entity);
			LogUtil.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			LogUtil.log("update failed", Level.SEVERE, re);
			throw re;
		}
	}

	public PadronElectoralSolicitante findById(PadronElectoralSolicitanteId id) {
		LogUtil.log("finding PadronElectoralSolicitante instance with id: "
				+ id, Level.INFO, null);
		try {
			PadronElectoralSolicitante instance = entityManager.find(
					PadronElectoralSolicitante.class, id);
			return instance;
		} catch (RuntimeException re) {
			LogUtil.log("find failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Find all PadronElectoralSolicitante entities with a specific property
	 * value.
	 * 
	 * @param propertyName
	 *            the name of the PadronElectoralSolicitante property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<PadronElectoralSolicitante> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<PadronElectoralSolicitante> findByProperty(String propertyName,
			final Object value, final int... rowStartIdxAndCount) {
		LogUtil.log(
				"finding PadronElectoralSolicitante instance with property: "
						+ propertyName + ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from PadronElectoralSolicitante model where model."
					+ propertyName + "= :propertyValue";
			Query query = entityManager.createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find by property name failed", Level.SEVERE, re);
			throw re;
		}
	}

	public List<PadronElectoralSolicitante> findByNombre(Object nombre,
			int... rowStartIdxAndCount) {
		return findByProperty(NOMBRE, nombre, rowStartIdxAndCount);
	}

	public List<PadronElectoralSolicitante> findByApellidopaterno(
			Object apellidopaterno, int... rowStartIdxAndCount) {
		return findByProperty(APELLIDOPATERNO, apellidopaterno,
				rowStartIdxAndCount);
	}

	public List<PadronElectoralSolicitante> findByApellidomaterno(
			Object apellidomaterno, int... rowStartIdxAndCount) {
		return findByProperty(APELLIDOMATERNO, apellidomaterno,
				rowStartIdxAndCount);
	}

	public List<PadronElectoralSolicitante> findByIdinconsistencia(
			Object idinconsistencia, int... rowStartIdxAndCount) {
		return findByProperty(IDINCONSISTENCIA, idinconsistencia,
				rowStartIdxAndCount);
	}

	public List<PadronElectoralSolicitante> findByEstadoinconsistencia(
			Object estadoinconsistencia, int... rowStartIdxAndCount) {
		return findByProperty(ESTADOINCONSISTENCIA, estadoinconsistencia,
				rowStartIdxAndCount);
	}

	public List<PadronElectoralSolicitante> findByDescripcioninconsistencia(
			Object descripcioninconsistencia, int... rowStartIdxAndCount) {
		return findByProperty(DESCRIPCIONINCONSISTENCIA,
				descripcioninconsistencia, rowStartIdxAndCount);
	}

	/**
	 * Find all PadronElectoralSolicitante entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<PadronElectoralSolicitante> all PadronElectoralSolicitante
	 *         entities
	 */
	@SuppressWarnings("unchecked")
	public List<PadronElectoralSolicitante> findAll(
			final int... rowStartIdxAndCount) {
		LogUtil.log("finding all PadronElectoralSolicitante instances",
				Level.INFO, null);
		try {
			final String queryString = "select model from PadronElectoralSolicitante model";
			Query query = entityManager.createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}

	public Long obtenerCantidadRegistros(Long procesoElectoralId) {
		String consulta = "select count(*) from padron_electoral_solicitante pes where pes.proceso_electoral_id="+procesoElectoralId;
		System.out.println(consulta);
		Query query = entityManager.createNativeQuery(consulta);
		BigDecimal resultado = (BigDecimal)query.getSingleResult();
		Long resultadoLong = resultado.longValue();
		return resultadoLong;
		/*String consulta = "SELECT count(p) FROM PadronElectoralSolicitante p where p.";
		Query query = entityManager.createQuery(consulta);
		Long resultado = Persistencia.getSingleResult(query,Long.class);
		return resultado;*/
	}
	
	@SuppressWarnings("unchecked")
	public List<PadronElectoralSolicitante> buscarPadronSolcitante(Long procesoElectoralId,
																	String numeroDocumento,
																	 String nombre,
																	 String apellidoPaterno,
																	 String apellidoMaterno,
																	 String incosistencia,
																	 String estadoIncosistencia,
																	 int inicio,
																	 int tamPagina) {
		if(numeroDocumento!=null && !numeroDocumento.equals("")){
			PadronElectoralSolicitanteId		id = new PadronElectoralSolicitanteId();
			id.setProcesoElectoralId(procesoElectoralId);
			id.setNumerodocumento(numeroDocumento);
			
			PadronElectoralSolicitante			padronElectoralSolicitante	= findById(id);
			List<PadronElectoralSolicitante>	listParametroEB				= new ArrayList<PadronElectoralSolicitante>();
			listParametroEB.add(padronElectoralSolicitante);
			
			return listParametroEB;
		}else{
			String consulta = "SELECT p FROM " +
							  "PadronElectoralSolicitante p " +
							  "where " +
							  "upper(nvl(p.nombre,' ')) like upper('%"+nombre+"%') " +
							  "and " +
							  "upper(nvl(p.apellidopaterno,' ')) like upper('%"+apellidoPaterno+"%') " +
							  "and " +
							  "upper(nvl(p.apellidomaterno,' ')) like upper('%"+apellidoMaterno+"%') " +
							  "and " +
							  "upper(nvl(p.idinconsistencia,' ')) like upper('%"+incosistencia+"%') " +
							  "and " +
							  "upper(nvl(p.estadoinconsistencia,' ')) like upper('%"+estadoIncosistencia+"%') ";
			
			System.out.println(consulta);
			
			Query query = entityManager.createQuery(consulta);
			
			query.setFirstResult(inicio);
			query.setMaxResults(tamPagina);
			
			//obtiene la lista de parametros
			List<PadronElectoralSolicitante> listParametroEB =  query.getResultList();
			
			return listParametroEB;
		}
	}

	@SuppressWarnings("unchecked")
	public int cantidadBuscarPadronSolcitante(Long procesoElectoralId,
			String numeroDocumento, String nombre, String apellidoPaterno,
			String apellidoMaterno, String incosistencia,
			String estadoIncosistencia) {
		if(numeroDocumento!=null && !numeroDocumento.equals("")){
			int cantidad = 0;
			PadronElectoralSolicitanteId		id = new PadronElectoralSolicitanteId();
			id.setProcesoElectoralId(procesoElectoralId);
			id.setNumerodocumento(numeroDocumento);
			PadronElectoralSolicitante			padronElectoralSolicitante	= findById(id);
			
			if(padronElectoralSolicitante!=null){
				cantidad = 1;
			}
			
			return cantidad;
			
		}else{
			String consulta = "SELECT p FROM " +
							  "PadronElectoralSolicitante p " +
							  "where " +
							  "upper(nvl(p.nombre,' ')) like upper('%"+nombre+"%') " +
							  "and " +
							  "upper(nvl(p.apellidopaterno,' ')) like upper('%"+apellidoPaterno+"%') " +
							  "and " +
							  "upper(nvl(p.apellidomaterno,' ')) like upper('%"+apellidoMaterno+"%') " +
							  "and " +
							  "upper(nvl(p.idinconsistencia,' ')) like upper('%"+incosistencia+"%') " +
							  "and " +
							  "upper(nvl(p.estadoinconsistencia,' ')) like upper('%"+estadoIncosistencia+"%')";
			
			System.out.println(consulta);
			Query query = entityManager.createQuery(consulta);
			List<PadronElectoralSolicitante> listParametroEB =  query.getResultList();
			
			return listParametroEB.size();
		}
	}
}